import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'

import Pages from 'vite-plugin-pages'
import Layouts from 'vite-plugin-vue-layouts'

import { resolve } from 'path'
import { mergeRouterPath } from './src/common/util/vite-plugin-pages-helper'

const devServer = require('./devServer.config')

// https://vitejs.dev/config/
export default (mode) => {
  const env = loadEnv(mode, process.cwd())
  return defineConfig({
    base: env.VITE_BASE_URL,
    plugins: [
      vue(),
      vueJsx(),
      Pages(
        {
          extensions: ['vue'],
          dirs: [{ dir: 'src/modules', baseRoute: '/' }],
          onRoutesGenerated: (routes) =>
            routes.map((router) => {
              router.path = mergeRouterPath(router.path)
              return router
            }),
          exclude: ['src/modules/widget/*.vue']
        }
      ),
      Layouts({
        layoutsDirs: 'src/common/layout',
        defaultLayout: 'default-layout'
      })
    ],
    resolve: {
      alias: {
        '@': resolve(__dirname, './src')
      }
    },
    build: {
      outDir: env.VITE_APP_OUT_DIR,
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true
        },
        output: {
          comments: true
        }
      }
    },
    server: devServer
  })
}
